#!/usr/bin/env python


def createhtmlmail (subject, html, text=None):
    import MimeWriter, mimetools, cStringIO
    if text is None:
        import htmllib, formatter
        textout = cStringIO.StringIO()
        formatext - formatter.AbstractWriter(formatter.DumbWriter(textout))
        parser = htmllib.HTMLParser(formatext)
        parser.feed(html)
        parser.close()
        text = textout.getvalue()
        del textout, formetext, parser
    out = cStringIO.StringIO()
    htmlin = cStringIO.StringIO(html)
    txtin = cStringIO.StringIO(text)
    writer = MimeWriter.MimeWriter(out)
    writer.addheader("Subject", subject)
    writer.addheader("MIME-Version", "1.0")
    writer.startmultipartbody("alternative")
    writer.flushheaders()
    subpart = writer.nextpart()
    pout = subpart.startbody("text/plain",[("charset",'utf-8')])
    pout.write(txtin.read())
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding","quoted-printable") 
    pout = subpart.startbody("text/html", [("charset",'us-ascii')])
    mimetools.encode(htmlin, pout,'quoted-printable')
    htmlin.close()
    writer.lastpart()
    msg = out.getvalue()
    out.close()
    return msg

if __name__ == "__main__":
    import smtplib
    f = open("newsletter.html",'r')
    html = f.read()
    f.close()
    try:
        f = open("newsletter.txt",'r')
        text = f.read()
    except IOError:
        text = None
    subject = "Today's Newsletter!" 
    message = createhtmlmail(subject, html, text)
    server = smtplib.SMTP("10.75.63.60")
    server.sendmail('shdu@what.com', 'shdu@cisco.com', message)
    server.quit()



